package com.subway.dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 数据连接帮助类
 */
public class BaseDao {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;
    static {
        String fileName="database.properties";
        Properties prsMap = new Properties();
        InputStream is = BaseDao.class.getClassLoader().getResourceAsStream( fileName );
        try {
            prsMap.load( is );
        }catch (IOException e){
            e.printStackTrace();
        }
        driver = prsMap.getProperty( "mysql.driver" );
        url = prsMap.getProperty( "mysql.url" );
        username = prsMap.getProperty( "mysql.username" );
        password = prsMap.getProperty( "mysql.password" );
        try {
            Class.forName( driver );
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }
    }

    public Connection openConnection(){
        Connection conn = null;
        try {
            conn =DriverManager.getConnection( url,username,password );
        }catch (SQLException e){
            e.printStackTrace();
        }
        return conn;
    }

    public  void  closeAll(ResultSet rs, PreparedStatement pstmt,Connection conn){
        try{
            if (rs!=null){
                rs.close();
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        try{
            if (pstmt!=null){
                pstmt.close();
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        try{
            if (conn!=null){
                conn.close();
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
    }
    public int executeUpdate(String sql,Object...objects){
        Connection conn = null;
        PreparedStatement pstmt=null;
        try {
            conn=this.openConnection();
            pstmt =conn.prepareStatement( sql );
            for (int i = 0; i < objects.length; i++) {
                pstmt.setObject( (i+1),objects[i] );

            }
           return pstmt.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            this.closeAll( null,pstmt,conn );
        }
        return 0;
    }
}

